package com.htfg.cardActivate.user.controller;

import com.google.gson.Gson;
import com.htfg.cardActivate.core.ResultData;
import com.htfg.cardActivate.user.entity.WeChatSession;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: 王晨缘
 * @Date: 2018/10/25 0025 14:31
 * @Description: 微信小程序接口
 */
@Api(value = "小程序授权")
@Controller
@RequestMapping("/smallProgrammer")
public class WxSmallProgrammer {
    @Value("${WxSmall.APPID}")
    private String APPID;
    @Value("${WxSmall.SECRET}")
    private String SECRET;

    @ApiOperation(value="小程序授权", notes="小程序授权" )
    @ApiImplicitParams({
            @ApiImplicitParam(name="code", value="授权码", required=true, dataType="String",paramType = "query"),
    })
    @ResponseBody
    @RequestMapping(value = "/login",method= RequestMethod.POST)
    public ResultData login(String code) {
        //微信的接口
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APPID +
                "&secret=" + SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        //进行网络请求,访问url接口
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        //根据返回值进行后续操作
        if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
            String sessionData = responseEntity.getBody();
            Gson gson = new Gson();
            //解析从微信服务器获得的openid和session_key;
            WeChatSession weChatSession = gson.fromJson(sessionData, WeChatSession.class);
            //获取用户的唯一标识
            String openid = weChatSession.getOpenid();
            //获取会话秘钥
            String session_key = weChatSession.getSession_key();
            //下面就可以写自己的业务代码了
            //最后要返回一个自定义的登录态,用来做后续数据传输的验证
            Map<String,String> map=new HashMap<>();
            map.put("openid",openid);
            map.put("session_key",session_key);
            return ResultData.successDate(map);
        }
        return ResultData.failDate("");
    }
}
